package org.testfire.support;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: granum
 * Date: Sep 12, 2007
 * Time: 12:13:50 AM
 *
 * This is here until I decide to package the Support Module into a Jar and include it.
 */
public class StringOutputStream extends OutputStream
{

	byte[] buf;
	List<byte[]> buffers = new ArrayList<byte[]>();
	int pos = 0;

	public StringOutputStream()
	{
		this(1000);
	}

	public StringOutputStream(int initialCapacity)
	{
		buf = new byte[initialCapacity];
	}

	public void write(int b) throws IOException
	{
		buf[pos++] = (byte) b;
		if (pos == buf.length)
		{
			buffers.add(buf);
			buf = new byte[buf.length];
			pos = 0;
		}
	}

	public String toString()
	{
		StringBuilder b = new StringBuilder();
		int count = buffers.size();
		for (byte[] bytes : buffers)
		{
			b.append(new String(bytes));
		}
		b.append(new String(buf, 0, pos));
		return b.toString();
	}


	public static String printException(Throwable t)
	{
		StringOutputStream stream = new StringOutputStream();
		PrintWriter stringWriter = new PrintWriter(stream);
		t.printStackTrace(stringWriter);
		stringWriter.flush();
		return stream.toString();
	}
}